// 打开开始界面
async function openStart() {
    // 工具函数
    // 获取存档id数组
    function getSlotIdArr() {
        return new Promise((resolve) => {
            indexedDB.open('yunyi', 1).onsuccess = (e) => {
                const gameSlot = e.target.result.transaction('gameSlot', 'readonly').objectStore('gameSlot');
                const getIdArr = gameSlot.getAllKeys();
                getIdArr.onsuccess = () => {
                    resolve(getIdArr.result);
                };
            };
        });
    }

    // 检查存档名是否合法、重复
    const nameLimit = 10;
    function checkNameValidity(name) {
        let valid = (name.trim() !== '' && name.length <= nameLimit);
        asset.slotIdArr.forEach((id) => {
            valid = valid && name !== id;
        });
        return valid;
    }
    const hintText = `存档名称不可以与以往存档重复，不可以为空或纯空格，且字符不可以超过${nameLimit}个`;

    asset = {
        openWay: 'new',
        currentSlot: NaN,
        slotIdArr: await getSlotIdArr(),
    };

    ctrller.startCtrller = new AbortController();

    // 设置开始新游戏按钮
    document.getElementById('start-new-game').addEventListener('click', openNewGame, {signal: ctrller.startCtrller.signal});
    function openNewGame() {
        ctrller.newGameCtrller = new AbortController();

        // 设置皮肤选择
        const skinOptions = document.querySelectorAll('.skin-option');
        for (let i = 0; i < skinOptions.length; i++) {
            skinOptions[i].style.backgroundImage = skinsArr[i].front;
            skinOptions[i].dataset.order = i;
            skinOptions[i].addEventListener(
                'click',
                function() {
                    skinOptions.forEach(opt => opt.classList.remove('selected'));
                    this.classList.add('selected');
                },
                {signal: ctrller.newGameCtrller.signal}
            );
        }

        // 设置开始按钮
        document.getElementById('start').addEventListener(
            'click',
            function() {
                const slotName = document.getElementById('slot-name').value;
                const canOpen = checkNameValidity(slotName);
                if (canOpen) {
                    asset.openWay = 'new';
                    asset.currentSlot = asset.slotIdArr.length; // 预设存档位
                    closeNewGame();
                    closeStart();
                    openGame();
                } else {
                    document.getElementById('new-game-hint').textContent = hintText;
                    document.getElementById('new-game-hint').style.display = 'block';
                }
            },
            {signal: ctrller.newGameCtrller.signal}
        );

        // 设置退出按钮
        document.getElementById('newGameExitBtn').addEventListener('click', closeNewGame, {signal: ctrller.newGameCtrller.signal});

        document.getElementById('newGame-screen').style.display = 'flex';

        // 关闭开始新游戏界面
        function closeNewGame() {
            document.getElementById('newGame-screen').style.display = 'none';
            ctrller.newGameCtrller.abort();
        }
    }

    // 设置 选择存档 按钮
    document.getElementById('select-slot').addEventListener('click', openSelectSlot, {signal: ctrller.startCtrller.signal});
    function openSelectSlot() {
        ctrller.selectSlotCtrller = new AbortController();

        // 设置存档选项
        if (asset.slotIdArr.length === 0) {
            document.getElementById('saved-slots').innerHTML = '还没有创建存档~';
        } else {
            for (let i = 0; i < asset.slotIdArr.length; i++) {
                // 设置存档区
                let slotId = asset.slotIdArr[i];
                const slotElement = document.createElement('div');
                slotElement.className = 'slot';
                slotElement.style.backgroundColor = '#64ddff';
                document.getElementById('saved-slots').appendChild(slotElement);

                // 设置存档名称
                const name = document.createElement('p');
                name.textContent = slotId;
                name.classList = 'slot-name';
                slotElement.appendChild(name);
                // 设置修改名称
                name.addEventListener(
                    'click',
                    function() {
                        // 切换为修改名称区
                        const inputNewName = document.createElement('input');
                        inputNewName.id = 'input-new-name';
                        inputNewName.type = 'text';
                        inputNewName.value = slotId;
                        inputNewName.placeholder = '存档名...';
                        name.replaceWith(inputNewName);

                        // 检测鼠标点击
                        document.addEventListener(
                            'click',
                            async function checkClick(event) {
                                if (!inputNewName.contains(event.target) && !name.contains(event.target)) {
                                    document.removeEventListener('click', checkClick);
                                    // 修改存档名
                                    if (checkNameValidity(inputNewName.value)) {
                                        const newName = inputNewName.value

                                        await new Promise((resolve) => {
                                            indexedDB.open('yunyi', 1).onsuccess = (e) => {
                                                const gameSlot = e.target.result.transaction('gameSlot', 'readwrite').objectStore('gameSlot');
                                                const getSlot = gameSlot.get(slotId);
                                                getSlot.onsuccess = () => {
                                                    const slot = {...getSlot.result, id: newName};
                                                    const deleteOld = gameSlot.delete(slotId);
                                                    deleteOld.onsuccess = () => {
                                                        gameSlot.put(slot).onsuccess = resolve;
                                                    };
                                                };
                                            };
                                        });

                                        slotId = newName;
                                        name.textContent = newName;
                                    } else { // 提醒名称无效
                                        autoCloseAlert(hintText, 5000);
                                    }
                                    inputNewName.replaceWith(name);
                                }
                            }
                        );
                    },
                    {signal: ctrller.selectSlotCtrller.signal}
                );

                // 设置“进入”按钮
                const comeInBtn = document.createElement('button');
                comeInBtn.textContent = '进入';
                comeInBtn.addEventListener(
                    'click',
                    function() {
                        asset.openWay = 'old';
                        asset.currentSlot = slotId;

                        closeSelectSlot();
                        closeStart();
                        openGame();
                    },
                    {signal: ctrller.selectSlotCtrller.signal}
                );
                slotElement.appendChild(comeInBtn);

                // 设置存档删除按钮
                const deleteBtn = document.createElement('button');
                deleteBtn.textContent = '删除';
                deleteBtn.addEventListener(
                    'click',
                    function() {
                        indexedDB.open('yunyi', 1).onsuccess = (e) => {
                            const slotData = e.target.result.transaction('gameSlot', 'readwrite').objectStore('gameSlot');

                            slotData.delete(slotId)
                                .onsuccess = (e) => {
                                    this.parentElement.remove();
                                };
                        };
                    }
                );
                slotElement.appendChild(deleteBtn);
            }
        }

        // 设置退出按钮
        document.getElementById('slotExitBtn').addEventListener(
            'click',
            closeSelectSlot,
            {signal: ctrller.selectSlotCtrller.signal}
        );

        document.getElementById('slot-screen').style.display = 'flex';

        // 关闭选择存档界面
        async function closeSelectSlot() {
            // 重新计算存档数
            asset.slotIdArr = await getSlotIdArr();

            document.getElementById('slot-screen').style.display = 'none';
            document.getElementById('saved-slots').innerHTML = '';
            ctrller.selectSlotCtrller.abort();
        }
    }

    document.getElementById('start-screen').style.display = 'flex';

    // 关闭开始界面
    function closeStart() {
        ctrller.startCtrller.abort();
        document.getElementById('start-screen').style.display = 'none';
    }
}